const fs              = require('fs'),
	vueServerRenderer = require('vue-server-renderer'),
	express           = require('express'),
	pug               = require('pug'),
	decode            = require('parse-entities'),
	config            = require('./config.js')


const bundleRenderer = vueServerRenderer.createBundleRenderer(fs.readFileSync('./dist/server/server-bundle.js', 'utf-8'))

const templateRender = pug.compileFile('./src/template/server.pug', {pretty: '\t'})

const app = express()

app.get('*', (req, res) => {
	bundleRenderer.renderToString({url: config.base+req.url}, (err, html) => {
		if (err) {
			console.log(err)
		}

		res.send(
			decode(
				templateRender({html, env: 'server'}).replace(
					/&#x([0-9a-fA-F]{4});/g,
					(match, p1) => String.fromCharCode(parseInt(p1, 16))
				)
			)
		)
	})
})

app.listen(8080, () => {
	console.log('listen on port: 8080')
})
